package com.example.rayal.satelitemenu.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;

import com.example.royal.satelitemenu.R;


/**
 * Created by Royal on 2016/1/20.
 */
public class SatelliteMenu extends ViewGroup{

    private static final int POS_LEFT_TOP = 0;
    private static final int POS_LEFT_BOTTOM = 1;
    private static final int POS_RIGHT_TOP = 2;
    private static final int POS_RIGHT_BOTTOM = 3;

    private Position mPosition = Position.RIGHT_BOTTOM;
    private int mRadius;
    private Status mCurStatus = Status.CLOSE;
    private RelativeLayout mCenterButton;
    private OnMenuClickListener mOnMenuClickListener;

    /**
     * 菜单位置的枚举类
     */
    public enum Position{
                LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM

        }

    /**
     * 菜单状态枚举类型
     */
    public enum Status {
        OPEN,CLOSE
    }

    /**
     * 点击子菜单的监听回调借接口
     */
    public interface OnMenuClickListener{
        void onClick(View view, int pos);
    }

    public void setOnMenuClickListener(OnMenuClickListener listener){
        this.mOnMenuClickListener = listener;
    }

    public SatelliteMenu(Context context) {
        this(context, null);
    }

    public SatelliteMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SatelliteMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,100,getResources().getDisplayMetrics());
        //获取自定义属性
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SatelliteMenu,defStyleAttr,0);

        int pos = a.getInt(R.styleable.SatelliteMenu_position,3);
        switch (pos){
            case POS_LEFT_TOP:
                mPosition = Position.LEFT_TOP;
                break;
            case POS_LEFT_BOTTOM:
                mPosition = Position.LEFT_BOTTOM;
                break;
            case POS_RIGHT_TOP:
                mPosition = Position.RIGHT_TOP;
                break;
            case POS_RIGHT_BOTTOM:
                mPosition = Position.RIGHT_BOTTOM;
                break;
            default:
                break;
        }

        mRadius = (int)a.getDimension(R.styleable.SatelliteMenu_radius,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,100,getResources().getDisplayMetrics()));
        Log.i("TAG","mPosition :"+ mPosition + "/n nmRadius:"+ mRadius);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();
        for (int i =0;i<count;i++){
            measureChild(getChildAt(i),widthMeasureSpec,heightMeasureSpec);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed){
            layoutCenterButton();

            int count = getChildCount();
            for(int i = 0;i < count - 1;i++){
                View child = getChildAt(i + 1);

                child.setVisibility(View.GONE);

                int cl = (int) (mRadius * Math.sin(Math.PI / 2 / (count - 2)
                        * i));
                int ct = (int) (mRadius * Math.cos(Math.PI / 2 / (count - 2)
                        * i));

                int cWidth = child.getMeasuredWidth();
                int cHeight = child.getMeasuredHeight();

                // 如果菜单位置在底部 左下，右下
                if (mPosition == Position.LEFT_BOTTOM
                        || mPosition == Position.RIGHT_BOTTOM)
                {
                    ct = getMeasuredHeight() - cHeight - ct;
                }
                // 右上，右下
                if (mPosition == Position.RIGHT_TOP
                        || mPosition == Position.RIGHT_BOTTOM)
                {
                    cl = getMeasuredWidth() - cWidth - cl;
                }
                child.layout(cl, ct, cl + cWidth, ct + cHeight);

            }
        }
    }

    /**
     * 定位主菜单按钮
     */
    private void layoutCenterButton(){
        mCenterButton = (RelativeLayout) getChildAt(0);
        int l = 0;
        int t = 0;
        int width = mCenterButton.getMeasuredWidth();
        int height = mCenterButton.getMeasuredHeight();
        switch (mPosition){
            case LEFT_TOP:
                l = 0;
                t = 0;
                break;
            case LEFT_BOTTOM:
                l = 0;
                t = getMeasuredHeight() - height;
                break;
            case RIGHT_TOP:
                l =  getMeasuredWidth() - width;
                t = 0;
                break;
            case RIGHT_BOTTOM:
                l = getMeasuredWidth() - width;
                t = getMeasuredHeight() -height;
                break;
        }

        mCenterButton.layout(l, t, l + width, t + height);
        mCenterButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //旋转动画
                rotateButton(v, 0f, 360f, 300);
                toggleMenu(300);
            }
        });
    }

    private void rotateButton(View v, float start, float end, int duration){
        RotateAnimation rotateAnimation = new RotateAnimation(start, end, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(duration);
        rotateAnimation.setFillAfter(true);
        v.startAnimation(rotateAnimation);
    }

    public void toggleMenu(int duration){
        //平移动画和旋转动画
        int count = getChildCount();
        for (int i = 0 ;i <count - 1 ; i++){
            final View childView = getChildAt(i + 1);
            childView.setVisibility(View.VISIBLE);
            int cl = (int) (mRadius * Math.sin(Math.PI / 2 / (count - 2)
                    * i));
            int ct = (int) (mRadius * Math.cos(Math.PI / 2 / (count - 2)
                    * i));

            int xflag = 1;
            int yflag = 1;
            //start
            //stop 0,0
            if(mPosition == Position.LEFT_TOP  || mPosition == Position.LEFT_BOTTOM){
                xflag = -1;
            }
            if(mPosition == Position.LEFT_TOP || mPosition == Position.RIGHT_TOP) {
                yflag = -1;
            }
            AnimationSet animationSet = new AnimationSet(true);
            Animation transAnim = null;
            if (mCurStatus == Status.CLOSE){ //To open
                transAnim = new TranslateAnimation(xflag * cl, 0, yflag * ct, 0);
                childView.setClickable(true);
                childView.setFocusable(true);
            }else { //To Close
                transAnim = new TranslateAnimation(0 ,xflag * cl, 0, yflag * ct);
                childView.setClickable(false);
                childView.setFocusable(false);
            }
            transAnim.setFillAfter(true);
            transAnim.setDuration(duration);
            transAnim.setStartOffset(i*50/count);
            transAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    if (mCurStatus == Status.CLOSE){
                        childView.setVisibility(View.GONE);
                    }

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            //旋转动画
            RotateAnimation rotateAnimation = new RotateAnimation(0, 720 ,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(duration);
            rotateAnimation.setFillAfter(true);
            animationSet.addAnimation(rotateAnimation);
            animationSet.addAnimation(transAnim);
            childView.startAnimation(animationSet);
            final int pos = i + 1;
            childView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                   if (mOnMenuClickListener != null){
                       mOnMenuClickListener.onClick(childView,pos);
                   }
                    menuItemAnim(pos - 1);
                    changeStatus();
                }
            });
        }
        //切换状态
        changeStatus();
    }
    //添加子菜单的点击动画
    private void menuItemAnim(int pos) {
      for (int i = 0 ;i <getChildCount()-1; i ++){
          View childView = getChildAt(i + 1);
          if (i == pos){
                childView.startAnimation(scaleBigAnim(300));
          }else {
              childView.startAnimation(scaleSmallAnim(300));
          }
          childView.setClickable(false);
          childView.setFocusable(false);
      }
    }

    private Animation scaleSmallAnim(int duration) {
        AnimationSet animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnim = new ScaleAnimation(1.0f,0.0f,1.0f,0.0f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f,0.0f);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(scaleAnim);
        animationSet.setFillAfter(true);
        animationSet.setDuration(duration);
        return animationSet;
    }

    private Animation scaleBigAnim(int duration) {
        AnimationSet animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnim = new ScaleAnimation(1.0f,4.0f,1.0f,4.0f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f,0.0f);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(scaleAnim);
        animationSet.setFillAfter(true);
        animationSet.setDuration(duration);
        return animationSet;
    }

    private void changeStatus(){
        mCurStatus =  ( mCurStatus == Status.CLOSE ? Status.OPEN : Status.CLOSE);
    }
}
